package app.models.system;

import app.security.DefaultAppShiroRealm;
import com.ifonly.activerecord.DbUtils;
import com.ifonly.activerecord.Model;
import com.ifonly.activerecord.Record;
import com.ifonly.activerecord.annotation.Table;
import com.ifonly.activerecord.annotation.Tx;
import com.ifonly.activerecord.sql.config.Sql;

import java.util.List;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2016-01-08 16:51
 * @since JDK 1.6
 */
@Table(name = "s_user_role")
public class UserRole extends Model {
    private static final long serialVersionUID = 5197068065549972139L;

    public List<Role> findRolesByUserId(long userId) {
        return DbUtils.list(Role.class, Sql.get("userRole.findRolesByUserId"), userId);
    }

    public Role findRoleByUserId(long userId) {
        List<Role> roles = findRolesByUserId(userId);
        if (roles == null || roles.isEmpty()) {
            return null;
        }

        if (roles.size() > 1) {
            throw new IllegalArgumentException("Role for User[id="+ userId +"] has " + roles.size() + " Roles");
        }
        return roles.get(0);
    }

    @Tx
    public void deleteUserAndUserRoles(int userId) {
        DbUtils.delete(Sql.get("userRole.deleteUserAndUserRoles"), userId);
        DbUtils.delete(Sql.get("user.deleteUserAndUserRoles"), userId);
    }

    public List<Record> findRoleWithUserId(int userId) {
        return DbUtils.list(Sql.get("userRole.findRoleWithUserId"), userId);
    }

    @Tx
    public void saveUserWithRoles(User user, String[] roleIds) {
        if (DbUtils.isNew(user)) {
            DefaultAppShiroRealm.setPasswordAndSalt(user);

            user.saveReturnGeneratedKey();
        } else {
            user.update();
        }

        long userId = user.getLongValue("id");

        DbUtils.delete(Sql.get("userRole.deleteUserAndUserRoles"), userId);

        int length = roleIds.length;
        Object[][] params = new Object[length][];
        for (int i = 0; i < length; i++) {
            params[i] = new Object[] {userId, roleIds[i]};
        }
        DbUtils.insertBatch(Sql.get("userRole.saveUserWithRoles"), params);
    }
}
